<template>
  <view class="pet-canvas-container">
    <!-- Canvas画布 -->
    <canvas 
      :canvas-id="canvasId"
      :id="canvasId"
      class="pet-canvas"
      :style="canvasStyle"
    ></canvas>
    
    <!-- 状态指示器 - 保留DOM实现 -->
    <view class="floating-status" v-if="showStatus">
      <view class="status-dot mood" :class="{ 'low': petData.mood < 30 }"></view>
      <view class="status-dot hunger" :class="{ 'low': petData.hunger < 20 }"></view>
      <view class="status-dot energy" :class="{ 'low': petData.energy < 15 }"></view>
    </view>
    
    <!-- 紧急指示器 - 保留DOM实现 -->
    <view class="emergency-indicators">
      <view 
        v-if="petData.mood < 20" 
        class="emergency-indicator mood-critical"
      >
        😢
      </view>
      <view 
        v-if="petData.hunger < 10" 
        class="emergency-indicator hunger-critical"
      >
        🍽️
      </view>
      <view 
        v-if="petData.energy < 10" 
        class="emergency-indicator energy-critical"
      >
        😴
      </view>
    </view>
  </view>
</template>

<script>
import PetRenderer from '@/utils/pet-renderer/PetRenderer.js'
import { getGlobalRenderLoop } from '@/utils/pet-renderer/RenderLoop.js'

export default {
  name: 'PetCanvas',
  props: {
    petData: {
      type: Object,
      required: true
    },
    currentAnimation: {
      type: String,
      default: 'idle'
    },
    isDragging: {
      type: Boolean,
      default: false
    },
    width: {
      type: Number,
      default: 100
    },
    height: {
      type: Number,
      default: 100
    }
  },
  
  data() {
    return {
      canvasId: 'petCanvas_' + Date.now(),
      ctx: null,
      renderer: null,
      renderLoop: null,
      showStatus: true,
      isInitialized: false,
      pixelRatio: 1
    }
  },
  
  computed: {
    canvasStyle() {
      return {
        width: this.width + 'rpx',
        height: this.height + 'rpx'
      }
    }
  },
  
  watch: {
    currentAnimation(newVal) {
      if (this.renderer) {
        this.renderer.updateAnimation(newVal, performance.now())
      }
    },
    
    isDragging(newVal) {
      if (this.renderer) {
        this.renderer.setDragging(newVal, performance.now())
      }
    }
  },
  
  mounted() {
    this.$nextTick(() => {
      this.initCanvas()
    })
  },
  
  beforeDestroy() {
    this.cleanup()
  },
  
  methods: {
    /**
     * 初始化Canvas
     */
    initCanvas() {
      try {
        // 获取系统信息
        const systemInfo = uni.getSystemInfoSync()
        this.pixelRatio = systemInfo.pixelRatio || 1
        
        // 创建Canvas上下文
        this.ctx = uni.createCanvasContext(this.canvasId, this)
        
        if (!this.ctx) {
          console.error('Failed to create canvas context')
          this.$emit('canvas-error', { message: 'Canvas not supported' })
          return
        }
        
        // 计算实际尺寸（rpx转px）
        const actualWidth = this.width * systemInfo.windowWidth / 750
        const actualHeight = this.height * systemInfo.windowWidth / 750
        
        // 创建渲染器
        this.renderer = new PetRenderer(this.ctx, {
          width: actualWidth,
          height: actualHeight,
          pixelRatio: this.pixelRatio,
          debugMode: false
        })
        
        // 设置初始动画
        this.renderer.updateAnimation(this.currentAnimation, performance.now())
        
        // 获取全局渲染循环
        this.renderLoop = getGlobalRenderLoop({
          targetFPS: 60,
          autoAdjustFPS: true,
          minFPS: 15
        })
        
        // 添加渲染器到渲染循环
        this.renderLoop.addRenderer(this.renderer)
        
        // 启动渲染循环
        if (!this.renderLoop.isRunning) {
          this.renderLoop.start()
        }
        
        this.isInitialized = true
        this.$emit('canvas-ready')
        
        console.log('PetCanvas initialized successfully')
        
      } catch (error) {
        console.error('Failed to initialize canvas:', error)
        this.$emit('canvas-error', { message: error.message })
      }
    },
    
    /**
     * 清理资源
     */
    cleanup() {
      if (this.renderLoop && this.renderer) {
        this.renderLoop.removeRenderer(this.renderer)
      }
      
      if (this.renderer) {
        this.renderer.destroy()
        this.renderer = null
      }
      
      this.ctx = null
      this.isInitialized = false
      
      console.log('PetCanvas cleaned up')
    },
    
    /**
     * 获取性能指标
     */
    getPerformanceMetrics() {
      if (this.renderLoop) {
        return this.renderLoop.getMetrics()
      }
      return null
    }
  }
}
</script>

<style scoped>
.pet-canvas-container {
  position: relative;
  width: 100rpx;
  height: 100rpx;
}

.pet-canvas {
  width: 100%;
  height: 100%;
}

/* 悬浮状态指示器 */
.floating-status {
  position: absolute;
  top: -15rpx;
  right: -15rpx;
  display: flex;
  flex-direction: column;
  gap: 6rpx;
  z-index: 10;
}

.status-dot {
  width: 12rpx;
  height: 12rpx;
  border-radius: 50%;
  background: #4caf50;
  border: 2rpx solid white;
  box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.2);
  animation: statusPulse 2s ease-in-out infinite;
}

.status-dot.mood {
  background: #4caf50;
}

.status-dot.hunger {
  background: #ff9800;
}

.status-dot.energy {
  background: #2196f3;
}

.status-dot.low {
  background: #f44336;
  animation: statusAlert 1s ease-in-out infinite;
}

@keyframes statusPulse {
  0%, 100% { transform: scale(1); opacity: 1; }
  50% { transform: scale(1.2); opacity: 0.7; }
}

@keyframes statusAlert {
  0%, 100% { transform: scale(1); opacity: 1; }
  50% { transform: scale(1.3); opacity: 0.5; }
}

/* 紧急状态指示器 */
.emergency-indicators {
  position: absolute;
  top: -25rpx;
  left: -25rpx;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
  z-index: 10;
}

.emergency-indicator {
  width: 20rpx;
  height: 20rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12rpx;
  animation: emergencyBlink 0.8s ease-in-out infinite;
  box-shadow: 0 3rpx 8rpx rgba(0, 0, 0, 0.3);
}

.emergency-indicator.mood-critical {
  background: #f44336;
}

.emergency-indicator.hunger-critical {
  background: #ff9800;
}

.emergency-indicator.energy-critical {
  background: #2196f3;
}

@keyframes emergencyBlink {
  0%, 100% { opacity: 1; transform: scale(1); }
  50% { opacity: 0.3; transform: scale(1.2); }
}
</style>
